package znbkBkfx.AboutKnowledgePoint;

import android.graphics.Color;
import android.text.Spannable;
import android.text.SpannableString;
import android.text.TextPaint;
import android.text.style.ClickableSpan;
import android.text.style.ForegroundColorSpan;
import android.util.Log;
import android.view.View;

import com.example.znbk.znbklibrary.util.LancooUtils;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class HighLightKeyWordUtil {

    /**
     * 关键字高亮显示
     * @param text    需要显示的文字
     * @param keyword  需要高亮的关键字
     * @param color   高亮颜色
     * @return 处理完后的结果
     */
    public static SpannableString highlight(String text, String[] keyword,String[] keywordCode, String color) {

        SpannableString spannableString = new SpannableString(text);

        for (int i = 0; i < keyword.length; i++) {
            Pattern pattern = Pattern.compile(keyword[i]);
            Matcher matcher = pattern.matcher(text);

            while (matcher.find()) {
                ForegroundColorSpan span = new ForegroundColorSpan(Color.parseColor(color));
//                spannableString.setSpan(span, matcher.start(), matcher.end(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
                spannableString.setSpan(new Clickable(listener,keyword[i],keywordCode[i]), matcher.start(), matcher.end(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
            }
        }
        return spannableString;
    }


    static class Clickable extends ClickableSpan {
        private final View.OnClickListener mListener;
        private String ClickKeyWord;
        private String ClickKeyWordCode;

        public Clickable(View.OnClickListener listener,String clickKeyWord,String clickKeyWordCode) {
            mListener = listener;
            ClickKeyWord = clickKeyWord;
            ClickKeyWordCode = clickKeyWordCode;
        }

        @Override
        public void updateDrawState(TextPaint ds) {
            ds.setColor(Color.parseColor("#ff0000"));//文本颜色
            ds.setUnderlineText(true);//是否有下划线
            ds.bgColor = Color.parseColor("#e3e3e3");//背景颜色
        }

        @Override
        public void onClick(View v) {
            if (null != mListener) {
                StrClickKeyWord = ClickKeyWord;
                StrClickKeyWordCode = ClickKeyWordCode;
                mListener.onClick(v);
            }
        }
    }

    private static String StrClickKeyWord = "";
    private static String StrClickKeyWordCode = "";
    static View.OnClickListener listener = new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            Log.e("==jerome==","========000=========StrClickKeyWord=========="+StrClickKeyWord);
            Log.e("==jerome==","========1111=========StrClickKeyWordCode=========="+StrClickKeyWordCode);
        }
    };

}
